package cn.com.shopec.erp.base.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import cn.com.shopec.erp.base.dao.ISupplierInfoDao;
import cn.com.shopec.erp.base.entity.SupplierInfo;
import cn.com.shopec.erp.base.vo.SupplierVo;
import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.orm.impl.HibernateEntityDao;
import cn.com.shopec.erp.common.utils.StringUtil;

@Repository
public class SupplierInfoDaoImpl extends HibernateEntityDao<SupplierInfo> implements ISupplierInfoDao {

	@Override
	public int updateSupplierFailure(String time) throws HibernateException {
		String sql = "update ";
		sql += "(select * from TBL_SUPPLIER_INFO t where t.delete_flag=" + SZSCMConstant.DELETE_FLAG_NO;
		sql += " and t.state=" + SZSCMConstant.STATE_LOCK;
		sql += " and t.contract_day_end < '" + time + "')";
		sql += "set state=" + SZSCMConstant.STATE_UNLOCK;
		Query query = this.createSQLQuery(sql);
		return query.executeUpdate();
	}

	@Override
	public List<?> getExportExcel(SupplierVo supVo) {
		StringBuffer sql = new StringBuffer();
		sql.append("select sup.account,sup.sup_name,sup.sup_short_name,sup.linkman, ");
		sql.append("sup.telephone_num,sup.mobile_phonenum,sup.email,sup.address, ");
		sql.append("sup.operate_type,sup.contract_day_strat,sup.contract_day_end, ");
		sql.append("sup.register_date,sup.state,sa.accounts_type,sa.brand_name, ");
		sql.append("sa.brand_code,sa.accounts_time,sa.accounts_way,sa.points_scale ");
		sql.append("from TBL_SUPPLIER_ACCOUNTS sa ");
		sql.append("left outer join TBL_SUPPLIER_INFO sup on sup.code = sa.code ");
		sql.append("where sa.delete_flag=1 and sup.delete_flag=1 ");
		if (StringUtil.isExist(supVo.getAccount())) {
			sql.append("and sup.account = '" + supVo.getAccount() + "' ");
		}
		if (StringUtil.isExist(supVo.getSupName())) {
			sql.append("and sup.sup_name like '%" + supVo.getSupName() + "%' ");
		}
		if (StringUtil.isExist(supVo.getCreateStartDate())) {
			sql.append("and sup.register_date > '" + supVo.getCreateStartDate() + "' ");
		}
		if (StringUtil.isExist(supVo.getCreateEndDate())) {
			sql.append("and sup.register_date < '" + supVo.getCreateEndDate() + "' ");
		}
		sql.append("order by sup.register_date desc");
		Query query = this.createSQLQuery(sql.toString());
		return query.list();
	}

	@Override
	public String getSupNameById(String id) {

		SupplierInfo supplierInfo = this.get("id", id);
		if (supplierInfo != null) {
			return supplierInfo.getSupName();
		}
		return null;
	}
}
